/*
 * Sybel.java
 *
 * Created on 28-nov-2011, 17.12.15
 */

package sybel;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTree;
import javax.swing.event.TreeModelEvent;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.tree.TreePath;
import javax.swing.tree.TreeSelectionModel;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.DOMImplementation;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.ls.DOMImplementationLS;
import org.w3c.dom.ls.LSOutput;
import org.w3c.dom.ls.LSSerializer;
import org.xml.sax.SAXException;
import sybel.pan.*;
import sybel.pan.util.TabbedPaneTitle;

/**
 *
 * @author Stefano
 */
public class Sybel extends javax.swing.JFrame {

    /** Creates new form Sybel */
    public Sybel() {
        initComponents();
        xml = new FileNameExtensionFilter("XML files", "xml");
        filechooser.addChoosableFileFilter(xml);
        filechooser.setFileFilter(xml);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jToolBar = new javax.swing.JToolBar();
        jButNewBehav = new javax.swing.JButton();
        jButOpenBehav = new javax.swing.JButton();
        jButtSaveAs = new javax.swing.JButton();
        jButNewEventExt = new javax.swing.JButton();
        jMainPanel = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTree = new javax.swing.JTree();
        jTabMainPane = new javax.swing.JTabbedPane();
        jMenuBar = new javax.swing.JMenuBar();
        jMenuFile = new javax.swing.JMenu();
        jMenuItemNB = new javax.swing.JMenuItem();
        jMenuIOpenBehav = new javax.swing.JMenuItem();
        jMenuISaveAs = new javax.swing.JMenuItem();
        jMenuINewFlow = new javax.swing.JMenuItem();
        jMenuEdit = new javax.swing.JMenu();
        jMenuItemFlow = new javax.swing.JMenuItem();
        jMenu1 = new javax.swing.JMenu();
        jMenuItemPrecond = new javax.swing.JMenuItem();
        jMenuItemPostcond = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jToolBar.setRollover(true);
        jToolBar.setBorderPainted(false);

        jButNewBehav.setText("New Behaviour");
        jButNewBehav.setFocusable(false);
        jButNewBehav.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jButNewBehav.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jButNewBehav.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButNewBehavActionPerformed(evt);
            }
        });
        jToolBar.add(jButNewBehav);

        jButOpenBehav.setText("Open behaviour");
        jButOpenBehav.setFocusable(false);
        jButOpenBehav.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jButOpenBehav.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jButOpenBehav.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButOpenBehavActionPerformed(evt);
            }
        });
        jToolBar.add(jButOpenBehav);

        jButtSaveAs.setText("Save as...");
        jButtSaveAs.setFocusable(false);
        jButtSaveAs.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jButtSaveAs.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jButtSaveAs.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtSaveAsActionPerformed(evt);
            }
        });
        jToolBar.add(jButtSaveAs);

        jButNewEventExt.setText("Add Event/Extension");
        jButNewEventExt.setFocusable(false);
        jButNewEventExt.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jButNewEventExt.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jButNewEventExt.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButNewEventExtActionPerformed(evt);
            }
        });
        jToolBar.add(jButNewEventExt);

        javax.swing.tree.DefaultMutableTreeNode treeNode1 = new javax.swing.tree.DefaultMutableTreeNode("root");
        jTree.setModel(new javax.swing.tree.DefaultTreeModel(treeNode1));
        jTree.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTreeMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(jTree);

        javax.swing.GroupLayout jMainPanelLayout = new javax.swing.GroupLayout(jMainPanel);
        jMainPanel.setLayout(jMainPanelLayout);
        jMainPanelLayout.setHorizontalGroup(
            jMainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jMainPanelLayout.createSequentialGroup()
                .addGap(10, 10, 10)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 172, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jTabMainPane, javax.swing.GroupLayout.DEFAULT_SIZE, 871, Short.MAX_VALUE)
                .addContainerGap())
        );
        jMainPanelLayout.setVerticalGroup(
            jMainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jMainPanelLayout.createSequentialGroup()
                .addGroup(jMainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 574, Short.MAX_VALUE)
                    .addComponent(jTabMainPane, javax.swing.GroupLayout.DEFAULT_SIZE, 574, Short.MAX_VALUE))
                .addContainerGap())
        );

        jMenuFile.setText("File");

        jMenuItemNB.setText("New Behaviour");
        jMenuItemNB.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItemNBActionPerformed(evt);
            }
        });
        jMenuFile.add(jMenuItemNB);

        jMenuIOpenBehav.setText("Open a Behaviour");
        jMenuIOpenBehav.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuIOpenBehavActionPerformed(evt);
            }
        });
        jMenuFile.add(jMenuIOpenBehav);

        jMenuISaveAs.setText("Save as...");
        jMenuISaveAs.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuISaveAsActionPerformed(evt);
            }
        });
        jMenuFile.add(jMenuISaveAs);

        jMenuINewFlow.setText("New Flow");
        jMenuFile.add(jMenuINewFlow);

        jMenuBar.add(jMenuFile);

        jMenuEdit.setText("Edit");

        jMenuItemFlow.setText("New Flow step");
        jMenuItemFlow.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItemFlowActionPerformed(evt);
            }
        });
        jMenuEdit.add(jMenuItemFlow);

        jMenu1.setText("Add Conditions");

        jMenuItemPrecond.setText("Preconditions");
        jMenuItemPrecond.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItemPrecondActionPerformed(evt);
            }
        });
        jMenu1.add(jMenuItemPrecond);

        jMenuItemPostcond.setText("Postconditions");
        jMenuItemPostcond.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItemPostcondActionPerformed(evt);
            }
        });
        jMenu1.add(jMenuItemPostcond);

        jMenuEdit.add(jMenu1);

        jMenuBar.add(jMenuEdit);

        setJMenuBar(jMenuBar);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jToolBar, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 1069, Short.MAX_VALUE)
            .addComponent(jMainPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jToolBar, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jMainPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    /*  Apre la finestra per la creazione di un nuovo behaviour */
    private void jMenuItemNBActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemNBActionPerformed
        CreateNewBehaviour();
    }//GEN-LAST:event_jMenuItemNBActionPerformed

    private void jButNewBehavActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButNewBehavActionPerformed
        CreateNewBehaviour();
    }//GEN-LAST:event_jButNewBehavActionPerformed

    /*  Gestione del click del mouse su elementi del jTree  */
    private void jTreeMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTreeMouseClicked
        /*  verifica del doppio click    */
        if(evt.getClickCount() == 2){
            TreePath selection = jTree.getSelectionPath();
            if(selection != null){
                addTabHandler(selection.getLastPathComponent());
            }
        }
    }//GEN-LAST:event_jTreeMouseClicked

    private void jButNewEventExtActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButNewEventExtActionPerformed
        CreateNewEvExt();
    }//GEN-LAST:event_jButNewEventExtActionPerformed

    private void jMenuItemFlowActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemFlowActionPerformed
        CreateNewEvExt();
    }//GEN-LAST:event_jMenuItemFlowActionPerformed

    private void jMenuItemPrecondActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemPrecondActionPerformed
        CreatePrePostCondition("pre");
    }//GEN-LAST:event_jMenuItemPrecondActionPerformed

    private void jMenuItemPostcondActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemPostcondActionPerformed
        CreatePrePostCondition("post");
    }//GEN-LAST:event_jMenuItemPostcondActionPerformed

    private void jMenuISaveAsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuISaveAsActionPerformed
        saveAs();
    }//GEN-LAST:event_jMenuISaveAsActionPerformed

    private void jButtSaveAsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtSaveAsActionPerformed
        saveAs();
    }//GEN-LAST:event_jButtSaveAsActionPerformed

    private void jButOpenBehavActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButOpenBehavActionPerformed
        OpenSybelDocument();
    }//GEN-LAST:event_jButOpenBehavActionPerformed

    private void jMenuIOpenBehavActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuIOpenBehavActionPerformed
        OpenSybelDocument();
    }//GEN-LAST:event_jMenuIOpenBehavActionPerformed

/**
 * Metodo che prende in input il nome del nodo del DOM richiesto
 * e aggiunge il rispettivo pannello creando una nuova Tab
 */
public void addTabHandler(Object selection){
    Node selectedNode = (Node)selection;
    try{
        Tags selectedTag = Tags.valueOf(selectedNode.getNodeName().toUpperCase());

        TabbedPaneTitle TabbedPaneTitle;
        switch(selectedTag){
            case ATTRIBUTES:
                jTabMainPane.add(new TabBehaviour(selectedNode.getParentNode()));
                TabbedPaneTitle = new TabbedPaneTitle(this,"Behaviour");
                break;
            case PARAMETERS:
                jTabMainPane.add(new Parameters());
                TabbedPaneTitle = new TabbedPaneTitle(this,"Parameters");
                break;
            case PRECONDITIONS:
                jTabMainPane.add(new Condition(selectedNode));
                TabbedPaneTitle = new TabbedPaneTitle(this,"Precondition");
                break;
            case POSTCONDITIONS:
                jTabMainPane.add(new Condition(selectedNode));
                TabbedPaneTitle = new TabbedPaneTitle(this,"Postconditions");
                break;
            case TRIGGER:
                jTabMainPane.add(new Trigger(selectedNode));
                TabbedPaneTitle = new TabbedPaneTitle(this,"Trigger");
                break;
            case FLOW:
                jTabMainPane.add(new Flow(selectedNode));
                TabbedPaneTitle = new TabbedPaneTitle(this,"Flow");
                break;
            case INTERACTION:
                jTabMainPane.add(new Interaction(selectedNode));
                TabbedPaneTitle = new TabbedPaneTitle(this,"Interaction");
                break;
            case HAPPENING:
                jTabMainPane.add(new Happening(selectedNode));
                TabbedPaneTitle = new TabbedPaneTitle(this,"Happening");
                break;
            case INCLUDE:
                jTabMainPane.add(new Include(selectedNode));
                TabbedPaneTitle = new TabbedPaneTitle(this,"Include");
                break;
            case ALTERNATIVE:
                jTabMainPane.add(new Alternative(selectedNode));
                TabbedPaneTitle = new TabbedPaneTitle(this,"Alternative");
                break;
            default:
                return;

        }
        jTabMainPane.setTabComponentAt(jTabMainPane.getTabCount()-1, TabbedPaneTitle);
        jTabMainPane.setSelectedIndex(jTabMainPane.getTabCount()-1);
    }catch(IllegalArgumentException il){
        return;
    }
    jTabMainPane.validate();
}

// variabile che segnala se una tab è già stata chiusa o meno
 private boolean closeCount = false;
/**
 * Metodo che viene richiamato alla pressione del tasto di chiusura di una tab aperta
 * @param pan il pannello da rimuovere dal tabbedPane
 */
public void closeTab(JPanel pan){
    int j = jTabMainPane.indexOfTabComponent(pan);
    boolean noerror;
    /* Se la tab è già stata chiusa una volta usa l'indice incrementato di 1*/
    if(!closeCount){
        noerror = savetab((JPanel)jTabMainPane.getComponent(j));
        closeCount = true;
    }
    else
        noerror = savetab((JPanel)jTabMainPane.getComponent(j+1));
    if(noerror)
        jTabMainPane.remove(j);
}

/**
 * Metodo che restituisce un intero che identifica il tipo di tab esaminando
 * la stringa passata in input
 *
 * @param s stringa rappresentante l'intero pannello del tipo "JPanel.toString()"
 * @return 0 se non è stata trovata nessuna delle tab conosciute
 * oppure un intero da 1 a 11 che rappresenta il tipo di pannello presente nella tab,
 */
public int checkTabsOpened(String s){
    for(int i=0; i<10; i++){
        if(s.contains(Tabs[i]))
            return i+1;
    }
    return 0;
}


public void OpenSybelDocument(){
    int fcValue = filechooser.showOpenDialog(this);
    if(fcValue == JFileChooser.APPROVE_OPTION){
        File input = filechooser.getSelectedFile();
        DOMbehaviour = loadDocument(input);
        InitializeJTree();
    }

}


/**
 * Metodo che legge un file xml e ne restituisce il DOM
 * @param un file xml
 * @return Document
 */
public Document loadDocument(File f){
    MyErrorHandler eh = new MyErrorHandler();
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(false);
    dbf.setValidating(true);
    try {
        DocumentBuilder db = dbf.newDocumentBuilder();
        db.setErrorHandler(eh);
        return db.parse(f);
    } catch (SAXException ex) {
        //gestita dall'error handler
    } catch (IOException ex) {
        Logger.getLogger(Sybel.class.getName()).log(Level.SEVERE, null, ex);
    } catch (ParserConfigurationException ex) {
        Logger.getLogger(Sybel.class.getName()).log(Level.SEVERE, null, ex);
    }
    return null;
}


/**
 * Metodo che effettua il salvataggio con nome dell'attuale contenuto del DOM
 * @return
 */
public boolean saveAs(){
    
    int fcValue = filechooser.showSaveDialog(this);

    if(fcValue == JFileChooser.APPROVE_OPTION){
        File output = filechooser.getSelectedFile();
        System.out.println(output);
        if(DOMbehaviour != null){
            try {
                saveDocument(DOMbehaviour, new FileWriter(output));
            } catch (IOException ex) {
                System.err.println("Errore di I/O: " + ex.getMessage());
            }
        }
    }

    return true;
}


public void saveDocument(Document d, Writer w) {
    DOMImplementation di = d.getImplementation();
    DOMImplementationLS dils = (DOMImplementationLS) di;

    LSSerializer lss = dils.createLSSerializer();
    LSOutput lso = dils.createLSOutput();

    lso.setCharacterStream(w);
    lso.setEncoding("ISO-8859-1");

    lss.getDomConfig().setParameter("format-pretty-print", true);

    lss.write(d, lso);
}

/**
 * riconosce il tipo di pannello passato per parametro e salva i dati in esso presenti
 * @param pan
 */
private boolean savetab(JPanel pan) {
    Node[] parentPath = null;

    int tab = checkTabsOpened(pan.toString());
    switch(tab){
            // Alternative
        case 1:
            Alternative alter = (Alternative)pan;
            Node alterParent = alter.AppendSavedData();
             // ----------  dati necessari al fire sul jTree --------------
            parentPath =  new Node[2];
            parentPath[0] = DOMbehaviour.getFirstChild();
            parentPath[1] = alterParent;
            break;

            // Flow
        case 2:
            Flow flow = (Flow)pan;
            Node flowNode = flow.saveData();
            // controllo della presenza di errori nel salvataggio del nodo
            if(flowNode == null)
                return false;

            // ----------  dati necessari al fire sul jTree --------------
            parentPath =  new Node[2];
            parentPath[0] = DOMbehaviour.getFirstChild();
            parentPath[1] = flowNode;
            break;

            // Happening
        case 3:
            Happening happ = (Happening)pan;
            Node happParent = happ.AppendSavedData();
             // ----------  dati necessari al fire sul jTree --------------
            parentPath =  new Node[2];
            parentPath[0] = DOMbehaviour.getFirstChild();
            parentPath[1] = happParent;
            break;

            // Include
        case 4:
            Include include = (Include)pan;
            Node includeParent = include.AppendSavedData();
             // ----------  dati necessari al fire sul jTree --------------
            parentPath =  new Node[2];
            parentPath[0] = DOMbehaviour.getFirstChild();
            parentPath[1] = includeParent;
            break;

            // Interaction
        case 5:
            Interaction interaction = (Interaction)pan;
            Node interParent = interaction.AppendSavedData();

            // ----------  dati necessari al fire sul jTree --------------
            parentPath =  new Node[2];
            parentPath[0] = DOMbehaviour.getFirstChild();
            parentPath[1] = interParent;
            break;

            // Parameters
        case 6:
            break;

            // Postconditions/Preconditions
        case 7:
            Condition postcond = (Condition)pan;
            Node postCondition = postcond.AppendSavedData();
            // controllo della presenza di errori nel salvataggio del nodo
            if(postCondition == null)
                return false;

            // ----------  dati necessari al fire sul jTree --------------
            parentPath =  new Node[2];
            parentPath[0] = DOMbehaviour.getFirstChild();
            parentPath[1] = postCondition;
            break;

            // TabBehaviour
        case 8:
            TabBehaviour tabbehav = (TabBehaviour)pan;
            Node behav = tabbehav.saveData();
            // controllo della presenza di errori nel salvataggio del nodo
            if(behav == null)
                return false;

            // ----------  dati necessari al fire sul jTree --------------
            parentPath =  new Node[1];
            parentPath[0] = DOMbehaviour.getFirstChild();
            break;

            // Trigger
        case 9:
            Trigger triggerPan = (Trigger)pan;
            Node triggerNode = triggerPan.saveData();

            // ----------  dati necessari al fire sul jTree --------------
            parentPath =  new Node[2];
            parentPath[0] = DOMbehaviour.getFirstChild();
            parentPath[1] = triggerNode;
            //model.fireTreeNodesChanged(new TreeModelEvent(DOMbehaviour, parentPath,indexChilds, NodeChilds));
            break;
    }
    // notifico il jTree del cambiamento effettuato sui nodi del DOM
    model.fireTreeStructureChanged(new TreeModelEvent(DOMbehaviour,parentPath));
    return true;
}

/**
 * Metodo che chiama una finestra di popup che consente la creazione di un
 * nuovo behaviour, per poi inizializzare il jTree ed il treemodel associato
 */
public void CreateNewBehaviour(){
        newBehav behaviour = new newBehav();
        DOMbehaviour = behaviour.show(this);
        InitializeJTree();
}

/**
 * Metodo che richiama una finestra di popup per l'inizializzazione di un nuovo
 * evento(interaction/happening) o estensione(alternative/include)
*/
public void CreateNewEvExt() {
    
    Node[] parentPath = new Node[2];

    if(jTree.getSelectionPath() == null || ((Node)jTree.getSelectionPath().getLastPathComponent()).getNodeName() != "flow"){
        JOptionPane.showMessageDialog(null, "You must select a Flow first");
    }
    else{
        
        newEventExt eventextension = new newEventExt((Node)jTree.getSelectionPath().getLastPathComponent());
        eventextension.show(this); // viene aggiunto il nuovo nodo ed inserito in newchild
        
        // ----------  dati necessari al fire sul jTree --------------
        parentPath[0] = DOMbehaviour.getFirstChild();
        parentPath[1] = (Node)jTree.getSelectionPath().getLastPathComponent();
        model.fireTreeStructureChanged(new TreeModelEvent(DOMbehaviour,parentPath));
    }
}

public void CreatePrePostCondition(String s){
    Document temp;
    Node[] parentPath = new Node[1];

    if(s == "pre"){
        temp = DomBuilder.addPrePostconditions("preconditions",DOMbehaviour);
    }else{
        temp = DomBuilder.addPrePostconditions("postconditions",DOMbehaviour);
    }
    if(temp != null)
        DOMbehaviour = temp;

    parentPath[0] = DOMbehaviour.getFirstChild();
    //model.fireTreeNodesInserted(new TreeModelEvent(DOMbehaviour, parentPath,children, newchild));
    model.fireTreeStructureChanged(new TreeModelEvent(DOMbehaviour,parentPath));
}

/**
 * Metodo che inizializza il treemodel instanzando poi il jTree
 */
public void InitializeJTree(){
    model = new DomModel(DOMbehaviour.getFirstChild());

    jTree = new JTree(model);
    jTree.addMouseListener(new java.awt.event.MouseAdapter() {
        public void mouseClicked(java.awt.event.MouseEvent evt) {
            jTreeMouseClicked(evt);
        }
    });

    jTree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
    jScrollPane1.setViewportView(jTree);
}


/**
 * metodo utile all'aggiornamento del jTree riepologativo a sinistra del frame principale
 */
public void refreshJTree(){
    model = new DomModel(DOMbehaviour.getFirstChild());

    jTree = new JTree(model);
    jTree.addMouseListener(new java.awt.event.MouseAdapter() {
        public void mouseClicked(java.awt.event.MouseEvent evt) {
            jTreeMouseClicked(evt);
        }
    });

    jTree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
    jScrollPane1.setViewportView(jTree);
    for (int i = 0; i < jTree.getRowCount(); i++) {
       jTree.expandRow(i);
    }
    jScrollPane1.setViewportView(jTree);
}

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Sybel().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButNewBehav;
    private javax.swing.JButton jButNewEventExt;
    private javax.swing.JButton jButOpenBehav;
    private javax.swing.JButton jButtSaveAs;
    private javax.swing.JPanel jMainPanel;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenuBar jMenuBar;
    private javax.swing.JMenu jMenuEdit;
    private javax.swing.JMenu jMenuFile;
    private javax.swing.JMenuItem jMenuINewFlow;
    private javax.swing.JMenuItem jMenuIOpenBehav;
    private javax.swing.JMenuItem jMenuISaveAs;
    private javax.swing.JMenuItem jMenuItemFlow;
    private javax.swing.JMenuItem jMenuItemNB;
    private javax.swing.JMenuItem jMenuItemPostcond;
    private javax.swing.JMenuItem jMenuItemPrecond;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTabbedPane jTabMainPane;
    private javax.swing.JToolBar jToolBar;
    private javax.swing.JTree jTree;
    // End of variables declaration//GEN-END:variables
    private Document DOMbehaviour;
    private DomModel model;
    private JFileChooser filechooser = new JFileChooser();
    private FileFilter xml;

    public String[] Tabs = {
        "Alternative",
        "Flow",
        "Happening",
        "Include",
        "Interaction",
        "Parameters",
        "Condition",
        "TabBehaviour",
        "Trigger"
    };

    public enum Tags{
        BEHAVIOUR,
        ATTRIBUTES,
        PARAMETERS,
        PRECONDITIONS,
        POSTCONDITIONS,
        TRIGGER,
        FLOW,
        INTERACTION,
        HAPPENING,
        INCLUDE,
        ALTERNATIVE
    }

}
